﻿using System;
using System.Linq;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web.Routing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Expressions;
using NotAClue.ComponentModel.DataAnnotations;
using NotAClue.Web;
using NotAClue.Web.DynamicData;

namespace DD_Extensions
{
    public partial class DetailsList : System.Web.UI.Page
    {
        protected MetaTable table;

        protected void Page_Init(object sender, EventArgs e)
        {
            table = DynamicDataRouteHandler.GetRequestMetaTable(Context);
            FormView1.SetMetaTable(table);
            DetailsDataSource.EntityTypeFilter = table.EntityType.Name;

            var childColumns = from cc in table.Columns.OfType<MetaChildrenColumn>()
                               where cc.GetAttribute<ShowChildTablesAttribute>() != null
                               orderby cc.GetAttribute<ShowChildTablesAttribute>().Order
                               select cc;

            FormView1.SetTableOptions(table);

            // Get child tables
            ChildrenFormView.GetTemplate(table, childColumns);

            foreach (var column in childColumns)
            {
                // disable partial render if a file upload column exists
                Page.DisablePartialRenderingForUpload(column.ChildTable);
            }

            // set post back URL
            //ListHyperLink.PostBackUrl = table.GetActionPath(PageAction.List);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Title = table.DisplayName;
            DetailsDataSource.Include = table.ForeignKeyColumnsNames;
        }

        protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
        {
            if (e.CommandName == DataControlCommands.CancelCommandName)
                Response.Redirect(table.ListActionPath + "?Canceled=True");
                //Response.Redirect(table.GetActionPath(PageAction.List)); // + Page.GetFilterValuesFromSession(table));
        }

        protected void FormView1_ItemDeleted(object sender, FormViewDeletedEventArgs e)
        {
            if (e.Exception == null || e.ExceptionHandled)
                Response.Redirect(table.GetActionPath(PageAction.List));
        }
    }
}
